import axios from 'axios'
import { useUserStore } from '@/store/modules/user'
import router from '@/router'
import { destroyTime } from '@/utils/timing'
import { destroyTime1 } from '@/utils/timing1'
import { destroyTime2 } from '@/utils/timing2'

import { message } from 'ant-design-vue'

const instance = axios.create({
  // baseURL: 'http://192.168.110.88:5201', // 马润丰
  // baseURL: 'http://192.168.110.83:5201', // 李鹏轩
  // baseURL: 'http://k8s-node-01.liangpiaovip.com:30080/ticket-expert', // 新 - 测试环境 - 2
  baseURL: 'http://crm.liangpiaovip.com', // 陈杰 - 新 - 正式环境 - 2025-1-21

  timeout: 5000,
})

instance.interceptors.request.use(
  config => {
    // @ts-ignore
    localStorage.setItem('baseUrl', config.baseURL)
    if (
      config.url == '/platform/quotationRule/quotationRuleVerify' ||
      config.url == '/film/order/filmOrderExcelOut' ||
      config.url == '/film/identify/getBeforehandQuotationByTask'
    ) {
      config.timeout = 45000
    }
    config.headers['user-token'] = localStorage.getItem('token')
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

const urlsToAllow: Array<string | undefined> = [
  '/film/order/filmOrderExcelOut',
  '/platform/user/userBalanceRecordExcelOut',
  '/fish/order/fishOrderExcelOut',
  '/fish/product/fishProductExcelOut',
  '/platform/wechatFans/balanceRecordExcelOut',
]

instance.interceptors.response.use(
  response => {
    let newToken = response.data.token
    if (newToken) {
      localStorage.setItem('token', newToken)
    }
    if (urlsToAllow.includes(response.config.url)) {
      return response
    }
    return response.data
  },
  error => {
    if (error.response) {
      const { status, config } = error.response
      if (status == 401) {
        destroyTime()
        destroyTime1()
        destroyTime2()
        const userStore = useUserStore()
        userStore.logout()
        router.push('/login')
        message.error('登录已过期，请重新登录')
      }
    } else {
      // console.error(`请求失败: ${error.message}`)
    }
    return Promise.reject(error)
  },
)

export default instance
